package com.eascs.caseManagement.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.caseManagement.dao.CaseManageDao;
import com.eascs.caseManagement.entity.CaseManagement;
import com.eascs.caseManagement.entity.CaseManagementHis;
import com.eascs.caseManagement.form.CaseManageForm;
import com.eascs.common.util.StringUtil;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

@Service
public class CaseManageService {
	Logger log =LoggerFactory.getLogger(CaseManageService.class);

	@Inject
	CaseManageDao  caseManageDao;
	
	
	
	public PageResult<Object[]> caseManageList(CaseManageForm vo) {

		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, vo.getPageSize(),vo.getPageIndex());

		StringBuilder sql = new StringBuilder();
		sql.append("select  t.id, t.num, t.refer_num,t.bill_code,t.loan_id, FORMAT(t.litigation_amount,2),t.first_filltime,FORMAT(t.recover_amount,2),b.loan_date, ADDDATE(b.loan_date,INTERVAL b.loan_term MONTH),t.update_time,t.updator from case_management t  LEFT join o2o_bank_loan_data b on t.bill_code =b.bill_code  where 1=1 and t.is_del='N' ");

		// 借款人
		if (vo.getLoanId()!= null && !"".equals(vo.getLoanId())) {
			sql.append(" and t.loan_id like ?");
			sqlPageQuery.addLikeParam(vo.getLoanId());
		}
		// 案号
		if (vo.getReferNum() != null && !"".equals(vo.getReferNum())) {
			sql.append(" and t.refer_num like ?");
			sqlPageQuery.addLikeParam(vo.getReferNum());
		}
		//编号
		if (vo.getNum() != null && !"".equals(vo.getNum())) {
			sql.append(" and t.num like ?");
			sqlPageQuery.addLikeParam(vo.getNum());
		}
		// 经办人
		if (vo.getOperator() != null && !"".equals(vo.getOperator())) {
			sql.append(" and t.operator like ?");
			sqlPageQuery.addLikeParam(vo.getOperator());
		}
		sql.append(" order by t.create_time desc ");
		sqlPageQuery.setQuerySql(sql.toString());
		PageResult<Object[]> caseManagepage = caseManageDao.findDataWithPage(sqlPageQuery);
		return caseManagepage;
	}
	
	
	
	public List<Object[]> findscommon(String code) {
		StringBuffer sql = new StringBuffer();
		sql.append(" select  ol.loanapply_no, ol.bill_code,CONCAT(ol.bill_code,'-',olu.user_full_name), olu.user_full_name,(SELECT GROUP_CONCAT(user_full_name SEPARATOR ',')   FROM o2o_loan_user r where r.sponsor_type='D' AND r.loanapply_no=ol.loanapply_no) ");
		sql.append(" from  o2o_loanapply ol LEFT JOIN o2o_loan_user olu ON ol.loan_id = olu.loan_id where /**DATA_PERMISSION(ol.LTD)**/ olu.spouse_id IS NULL AND olu.loanapply_no = ol.loanapply_no ");
		sql.append(" and ol.loan_flg='Y'  and ol.wf_type ='DC'  and ol.bill_code like ? GROUP BY ol.bill_code LIMIT 10 ");
		return caseManageDao.findObjectsList(sql.toString(), "%" + code + "%");
	}
	
	//@Transactional(transactionManager = "transactionManager")
	public Map<String,String> addSave(CaseManagement vo){
		
		User user=UserHolder.getUser();
		String flag="success";
		Map<String,String>  map=new HashMap<String,String>();
		if(vo!=null&&StringUtil.isNotBlank(vo.getId())){//修改
			CaseManagement cmu = caseManageDao.getById(CaseManagement.class, vo.getId());
			vo.setCreateId(cmu.getCreateId());
			vo.setCreateor(cmu.getCreateor());
			vo.setCreateTime(cmu.getCreateTime());
			CaseManagement cms = setCaseManage(cmu,vo,user,"update");
			try {
				caseManageDao.updateById(cms);
			} catch (Exception e) {
				flag="fail";
				log.error("修改案件管理数据库异常：[{}]", e.getMessage());
			}
		}else{//新增
			CaseManagement cm=new CaseManagement();
			CaseManagement cms = setCaseManage(cm,vo,user,"add");
			try {
				caseManageDao.insert(cms);
			} catch (Exception e) {
				flag="fail";
				log.error("新增案件管理数据库异常：[{}]", e.getMessage());
			}
		}
		try {
			CaseManagementHis cmh = setCaseManageHis(vo, user);
			caseManageDao.insert(cmh);
		} catch (Exception e) {
			flag="fail";
			log.error("新增案件管理历史记录数据库异常：[{}]", e.getMessage());
		}
		map.put("flag", flag);
		return map;
	}


	
	
	public boolean  updateCaseManageStatus(String id){
		return  caseManageDao.execute("update case_management set is_del='Y' where id =? ", id)>0?true:false;
	}
	
	public CaseManagement getCaseManageById(String id){
		return caseManageDao.getById(CaseManagement.class, id);
	}
	
	public CaseManagementHis getCaseManageHisById(String id){
		return caseManageDao.getById(CaseManagementHis.class, id);
	}
	
	public PageResult<Object[]> caseManageHisList(CaseManageForm vo) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, vo.getPageSize(),vo.getPageIndex());
		StringBuilder sql = new StringBuilder();
		sql.append("select t.id,  t.bill_code, t.update_time,t.updator from case_management_his t  where  t.bill_code = ? ");
		sqlPageQuery.addParam( vo.getBillCode());
		sqlPageQuery.setQuerySql(sql.toString());
		PageResult<Object[]> caseManagepage = caseManageDao.findDataWithPage(sqlPageQuery);
		return caseManagepage;
	}
	
	
	
	
	
	
	
	
	
	
	
	

	private CaseManagementHis setCaseManageHis(CaseManagement vo, User user) {
		CaseManagementHis cmh =new  CaseManagementHis();
		cmh.setBillCode(vo.getBillCode());
		cmh.setLoanId(vo.getLoanId());
		cmh.setNum(vo.getNum());
		cmh.setReferNum(vo.getReferNum());
		cmh.setOperator(vo.getOperator());
		cmh.setPrincipalInvolved(vo.getPrincipalInvolved());
		cmh.setInterestInvolved(vo.getInterestInvolved());
		cmh.setDefaulltInvolved(vo.getDefaulltInvolved());
		cmh.setLitigationAmount(vo.getLitigationAmount());
		cmh.setSummary(vo.getSummary());
		cmh.setFirstCourt(vo.getFirstCourt());
		cmh.setFirstFilltime(vo.getFirstFilltime());
		cmh.setCaseContact(vo.getCaseContact());
		cmh.setPrepaidFee(vo.getPrepaidFee());
		cmh.setSecurityFee(vo.getSecurityFee());
		cmh.setRecoverAmount(vo.getRecoverAmount());
		cmh.setLossAmount(vo.getLossAmount());
		cmh.setLossRate(vo.getLossRate());
		cmh.setPreservationLitigation(vo.getPreservationLitigation());
		cmh.setProceedingProgress(vo.getProceedingProgress());
		cmh.setPropertyClues(vo.getPropertyClues());
		cmh.setRemark(vo.getRemark());
		cmh.setSponsor(vo.getSponsor());
		cmh.setCaseStatus(vo.getCaseStatus());
		cmh.setIsDel("N");
		if(user!=null){
			cmh.setCreateId(vo.getCreateId()==null?user.getCode():vo.getCreateId());
			cmh.setCreateor(vo.getCreateor()==null?user.getCname():vo.getCreateor());
			cmh.setUpdateId(user.getCode());
			cmh.setUpdator(user.getCname());
		}
		cmh.setCreateTime(vo.getCreateTime()==null?new Date():vo.getCreateTime());
		cmh.setUpdateTime(new Date());
		return cmh;
	}

	
	private CaseManagement setCaseManage(CaseManagement cm ,CaseManagement vo, User user,String type) {
		cm.setBillCode(vo.getBillCode());
		cm.setLoanId(vo.getLoanId());
		cm.setNum(vo.getNum());
		cm.setReferNum(vo.getReferNum());
		cm.setOperator(vo.getOperator());
		cm.setPrincipalInvolved(vo.getPrincipalInvolved());
		cm.setInterestInvolved(vo.getInterestInvolved());
		cm.setDefaulltInvolved(vo.getDefaulltInvolved());
		cm.setLitigationAmount(vo.getLitigationAmount());
		cm.setSummary(vo.getSummary());
		cm.setFirstCourt(vo.getFirstCourt());
		cm.setFirstFilltime(vo.getFirstFilltime());
		cm.setCaseContact(vo.getCaseContact());
		cm.setPrepaidFee(vo.getPrepaidFee());
		cm.setSecurityFee(vo.getSecurityFee());
		cm.setRecoverAmount(vo.getRecoverAmount());
		cm.setLossAmount(vo.getLossAmount());
		cm.setLossRate(vo.getLossRate());
		cm.setPreservationLitigation(vo.getPreservationLitigation());
		cm.setProceedingProgress(vo.getProceedingProgress());
		cm.setPropertyClues(vo.getPropertyClues());
		cm.setRemark(vo.getRemark());
		cm.setSponsor(vo.getSponsor());
		cm.setCaseStatus(vo.getCaseStatus());
		cm.setIsDel("N");
		if(user!=null){
			if("add".equals(type)){
				cm.setCreateId(user.getCode());
				cm.setCreateor(user.getCname());
			}else{
				cm.setUpdateId(user.getCode());
				cm.setUpdator(user.getCname());
			}
		}
		if("add".equals(type)){
			cm.setCreateTime(new Date());
		}else{
			cm.setUpdateTime(new Date());
		}
		return cm;
	}
}
